<template>
  <div class="ele-body">
    <a-row :gutter="16">
      <!-- 左侧列表 -->
      <a-col :lg="4" :md="10" :sm="24" :xs="24" class="left-menu-height">
        <devicetype-tree
          :devicetypeList="devicetypeList"
          v-model:currentSelectDeviceId="where.dceId"
          @changeNodeSelect="reload"
        />
      </a-col>
      <!-- 右侧用户管理表格 -->
      <a-col :lg="20" :md="14" :sm="24" :xs="24">
        <!-- 搜索表单 -->
        <div class="block-interval">
          <a-card :bordered="false">
            <a-form layout="inline" :model="where">
              <a-row>

                <a-form-item label="设备ID:">
                  <a-input v-model:value.trim="where.recordId" placeholder="请输入设备ID" allow-clear />
                </a-form-item>

                <a-form-item label="状态:">
                  <a-select
                    show-search
                    v-model:value="where.recordStatus"
                    style="width: 120px"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    allow-clear
                  >
                    <a-select-option value='1'>在线</a-select-option>
                    <a-select-option value='2'>离线</a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item label="设备编码:">
                  <a-input v-model:value.trim="where.recordNo" placeholder="请输入设备编码" allow-clear />
                </a-form-item>

                <a-form-item label="所属牧场:" name="orgId">
                  <a-select
                    show-search
                    v-model:value="where.orgId"
                    placeholder="请选择所属牧场"
                    style="width: 205px;"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    @change="selectRanch"
                    allow-clear
                    @clear="clearRanchRelated"
                  >
                    <a-select-option v-for="item in ranchList" :key="item.ranchId" >
                      {{ item.ranchName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>


                <a-form-item label="所属牛舍:" name="oxtId">
                  <a-select
                    show-search
                    v-model:value="where.oxtId"
                    placeholder="请选择所属牛舍"
                    style="width: 200px"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    @change="selectOxtall"
                    allow-clear
                    @clear="clearOxtallRelated"
                  >
                    <a-select-option v-for="item in oxtallList" :key="item.oxtallId" >
                      {{ item.oxtallName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item label="所属区域:" name="areaId">
                  <a-select
                    show-search
                    v-model:value="where.areaId"
                    placeholder="请选择所属区域"
                    style="width: 200px"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    allow-clear
                  >
                    <a-select-option v-for="item in areaList" :key="item.areaId" >
                      {{ item.areaName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item class="ele-text-center">
                  <a-space>
                    <a-button type="primary" @click="reload">查询</a-button>
                    <a-button @click="reset">重置</a-button>
                  </a-space>
                </a-form-item>

              </a-row>
            </a-form>
          </a-card>
        </div>

        <!-- 表格 -->
        <div>
          <a-card :bordered="false" class="table-height">
            <ele-pro-table
              ref="table"
              row-key="recordId"
              :datasource="datasource"
              :columns="columns"
              :where="where"
              v-model:selection="selection"
              :scroll="{ x: 1300, y: 1000 }"
            >
              <!-- table上边工具栏 -->
              <template #toolbar>
                <a-space v-permission="['PROPERTY_DEVICELIST_ADD_BUTTON']">
                  <a-button type="primary" @click="openEdit()">
                    <template #icon>
                      <plus-outlined />
                    </template>
                    <span>新建</span>
                  </a-button>
                </a-space>
              </template>

              <template #bodyCell="{ column, record }">
                <!-- 排序字段可编辑 -->
                <template v-if="column.dataIndex === 'csort'">
                  <div v-if="editingId === record.recordId && editingField === 'csort'">
                    <div style="display: flex; flex-direction: column;">
                      <a-input 
                        v-model:value="editingValue" 
                        style="width: 100px; margin-bottom: 4px;"
                        placeholder="请输入排序值"
                      />
                      <div style="display: flex; justify-content: center;">
                        <a-button type="link" size="small" @click="saveSort(record)" style="padding: 0 8px;">
                          <check-outlined />
                        </a-button>
                        <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                          <close-outlined />
                        </a-button>
                      </div>
                    </div>
                  </div>
                  <div v-else>
                    <a-space>
                      <span>{{ record.csort }}</span>
                      <a-button type="link" size="small" @click="startEdit(record)">
                        <edit-outlined />
                      </a-button>
                    </a-space>
                  </div>
                </template>
                
                <!-- 牧场字段可编辑 -->
                <template v-if="column.dataIndex === 'ranchName'">
                  <div v-if="editingId === record.recordId && editingField === 'ranchName'">
                    <div style="display: flex; flex-direction: column; position: relative;">
                      <a-select
                        v-model:value="editingRanchId"
                        style="width: 180px; margin-bottom: 4px;"
                        placeholder="请选择牧场"
                        :dropdown-style="{ maxWidth: '300px' }"
                        :dropdown-match-select-width="false"
                        placement="bottomLeft"
                      >
                        <a-select-option v-for="item in tempRanchList" :key="item.ranchId">
                          {{ item.ranchName }}
                        </a-select-option>
                      </a-select>
                      <div style="display: flex; justify-content: center;">
                        <a-button type="link" size="small" @click="saveRanch(record)" style="padding: 0 8px;">
                          <check-outlined />
                        </a-button>
                        <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                          <close-outlined />
                        </a-button>
                      </div>
                    </div>
                  </div>
                  <div v-else>
                    <a-space>
                      <span>{{ record.ranchName }}</span>
                      <a-button type="link" size="small" @click="startEditRanch(record)">
                        <edit-outlined />
                      </a-button>
                    </a-space>
                  </div>
                </template>
                
                <!-- 牛舍字段可编辑 -->
                <template v-if="column.dataIndex === 'oxtallName'">
                  <div v-if="editingId === record.recordId && editingField === 'oxtallName'">
                    <div style="display: flex; flex-direction: column;">
                      <a-select
                        v-model:value="editingOxtallId"
                        style="width: 120px; margin-bottom: 4px;"
                        placeholder="请选择牛舍"
                      >
                        <a-select-option v-for="item in tempOxtallList" :key="item.oxtallId">
                          {{ item.oxtallName }}
                        </a-select-option>
                      </a-select>
                      <div style="display: flex; justify-content: center;">
                        <a-button type="link" size="small" @click="saveOxtall(record)" style="padding: 0 8px;">
                          <check-outlined />
                        </a-button>
                        <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                          <close-outlined />
                        </a-button>
                      </div>
                    </div>
                  </div>
                  <div v-else>
                    <a-space>
                      <span>{{ record.oxtallName }}</span>
                      <a-button type="link" size="small" @click="startEditOxtall(record)">
                        <edit-outlined />
                      </a-button>
                    </a-space>
                  </div>
                </template>
                
                <!-- 区域字段可编辑 -->
                <template v-if="column.dataIndex === 'areaName'">
                  <div v-if="editingId === record.recordId && editingField === 'areaName'">
                    <div style="display: flex; flex-direction: column;">
                      <a-select
                        v-model:value="editingAreaId"
                        style="width: 120px; margin-bottom: 4px;"
                        placeholder="请选择区域"
                      >
                        <a-select-option v-for="item in tempAreaList" :key="item.areaId">
                          {{ item.areaName }}
                        </a-select-option>
                      </a-select>
                      <div style="display: flex; justify-content: center;">
                        <a-button type="link" size="small" @click="saveArea(record)" style="padding: 0 8px;">
                          <check-outlined />
                        </a-button>
                        <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                          <close-outlined />
                        </a-button>
                      </div>
                    </div>
                  </div>
                  <div v-else>
                    <a-space>
                      <span>{{ record.areaName }}</span>
                      <a-button type="link" size="small" @click="startEditArea(record)">
                        <edit-outlined />
                      </a-button>
                    </a-space>
                  </div>
                </template>

                <!-- 牛栏字段可编辑 -->
                <template v-if="column.dataIndex === 'fenceName'">
                  <div v-if="editingId === record.recordId && editingField === 'fenceName'">
                    <div style="display: flex; flex-direction: column;">
                      <a-select
                        v-model:value="editingFenceId"
                        style="width: 120px; margin-bottom: 4px;"
                        placeholder="请选择牛栏"
                      >
                        <a-select-option v-for="item in tempFenceList" :key="item.fenceId">
                          {{ item.fenceName }}
                        </a-select-option>
                      </a-select>
                      <div style="display: flex; justify-content: center;">
                        <a-button type="link" size="small" @click="saveFence(record)" style="padding: 0 8px;">
                          <check-outlined />
                        </a-button>
                        <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                          <close-outlined />
                        </a-button>
                      </div>
                    </div>
                  </div>
                  <div v-else>
                    <a-space>
                      <span>{{ record.fenceName }}</span>
                      <a-button type="link" size="small" @click="startEditFence(record)">
                        <edit-outlined />
                      </a-button>
                    </a-space>
                  </div>
                </template>
                
                <!-- 其他列的模板 -->
                <template v-if="column.key === 'statuscolumn'">
                  <a-tag v-if="record.recordStatus == 1" color="green">在线</a-tag>
                  <a-tag v-else color="red">离线</a-tag>
                </template>

                <!-- table操作栏按钮 -->
                <template v-if="column.key === 'action'">
                  <a-space>
                    <div v-permission="['PROPERTY_DEVICELIST_DEL_BUTTON']">
                      <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                        <a class="ele-text-danger">删除</a>
                      </a-popconfirm>
                    </div>
                    <a-divider v-permission="['PROPERTY_DEVICELIST_DEL_BUTTON']" type="vertical" />
                    <a-dropdown>
                      <a class="ant-dropdown-link" @click.prevent>
                        更多
                        <DownOutlined />
                      </a>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item>
                            <a @click="openEdit(record)" v-permission="['PROPERTY_DEVICELIST_UPDATE_BUTTON']">修改</a>
                          </a-menu-item>
                          <a-menu-item >
                            <a @click="openManager(record)">管理</a>
                          </a-menu-item>
                          <a-menu-item v-if="record.switchMappingDeviceRecordDTO != null">
                            <a @click="openPhaseManager(record.switchMappingDeviceRecordDTO)">电源管理</a>
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </template>
              </template>
            </ele-pro-table>
          </a-card>
        </div>
      </a-col>
    </a-row>

    <!-- 编辑弹窗 -->
    <devicelist-edit v-if="showEdit" v-model:visible="showEdit" :data="current" @done="reloadCurrent" />
    <component :is="currentView" v-if='showDeviceManager'  v-model:visible="showDeviceManager" :data="current" />

    <component :is="phaseView" v-if='showPhaseManager'  v-model:visible="showPhaseManager" :data="phaseCurrenData" />

    <!-- 设备管理 -->
    <!-- <device-spray-ctocabinet-modal v-if='showDeviceManager'  v-model:visible="showDeviceManager" :data="current" />-->
  </div>
</template>

<script>
import { PlusOutlined } from '@ant-design/icons-vue';
import { DeviceRecordApi } from '@/api/property/DeviceRecordApi';
import { DeviceApi } from '@/api/property/DeviceApi';
import { AreaApi } from '@/api/property/AreaApi';
import {FenceApi} from '@/api/property/FenceApi';
import DevicelistEdit from './devicelist-edit.vue';
import DevicetypeTree from './devicetype-tree.vue';
import DeviceSprayCtocabinetModal from './spray/ctocabinet-modal.vue'
import DeviceWatermeterModal from './watermeter/meter-modal.vue';
import DeviceSpraymianboardModal from './spraymainboard/mainboard-modal.vue'
import DeviceEnvControlModal from './envcontrol/envcontrol-modal.vue'
import DeviceLuoxungasModal from './luoxungas/luoxungas-modal.vue'
import DeviceLuoxunwaterpressureModal from './luoxunwaterpressure/luoxunwaterpressure-modal.vue'
import DeviceLuoxunwaterposModal from './luoxunwaterpos/luoxunwaterpos-modal.vue'
import DeviceLuoxunSimplephaseModal from './luoxunsimplephase/luoxunsimplephase-modal.vue'
import DeviceLuoxunThreephaseModal from './luoxunthreephase/luoxunthreephase-modal.vue'
import DeviceNoneManagerModal from './device-none-manager-modal.vue'
import DeviceSinkManagerModal from './sink/sink-modal.vue'
import DeviceLuoxunPulsationModal from './luoxunpulsation/luoxunpulsation-modal.vue'
import DeviceSinkGatewayManagerModal from './sinkgateway/sinkgateway-modal.vue'
import DeviceCattleHeartbeatModal from './cattleheartbeat/heartbeat-modal.vue'
import DeviceDrinkstationModal from './drinkingstation/drinkingstation-modal.vue'
import DeviceFootpositionModal from './cattlesports/footposition/positionfoot-modal.vue'
import DeviceLiedownModal from './cattlesports/liedown/liedown-modal.vue'
import DeviceStomachModal from './cattlesports/stomach/stomach-modal.vue'
import DeviceCattlesportEstrusModal from './cattlesports/estrus/estrus-modal.vue'
import DeviceDrinkheartingModal from './drinkhearting/drinkhearting-modal.vue'
import DeviceVehicleModal from './vehicle/vehicle-modal.vue'
import DeviceRollershadesModal from './rollershades/rollershades-modal.vue'
import DeviceBasaModal from './basa/basa-modal.vue'
import DeviceSlurryscraperModal from './slurryscraper/slurryscraper-modal.vue'
import DeviceSpraycameraModal from './spraycamera/spraycamera-modal.vue'
import DeviceSprayfanlinkcameraModal from './sprayfanlinkcamera/sprayfanlinkcamera-modal.vue'
import DeviceAiedgecomputerModal from './aiedgecomputer/aiedgecomputer-modal.vue'
import DevicePowerMonitorModal from './powermonitorclient/powermonitor-modal.vue'
import { RanchApi } from '@/api/property/RanchApi';
import { OxtallApi } from '@/api/property/OxtallApi';
import { message } from 'ant-design-vue';
import { DownOutlined } from '@ant-design/icons-vue';
import {useUserStore} from "@/store/modules/user";
import { EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons-vue';

export default {
  name: 'DeviceRecord',
  components: {
    PlusOutlined,
    DevicelistEdit,
    DevicetypeTree,
    DeviceSprayCtocabinetModal,
    DeviceWatermeterModal,
    DeviceSpraymianboardModal,
    DeviceEnvControlModal,
    DeviceLuoxungasModal,
    DeviceLuoxunSimplephaseModal,
    DeviceLuoxunThreephaseModal,
    DeviceLuoxunPulsationModal,
    DeviceNoneManagerModal,
    DeviceLuoxunwaterpressureModal,
    DeviceLuoxunwaterposModal,
    DeviceSinkManagerModal,
    DownOutlined,
    DeviceSinkGatewayManagerModal,
    DeviceCattleHeartbeatModal, //奶牛呼吸心跳监测设备
    DeviceDrinkstationModal, //喷淋饮水台
    DeviceFootpositionModal, //定位环脚
    DeviceVehicleModal, //车辆黑匣子
    DeviceLiedownModal, //牛躺卧设备
    DeviceCattlesportEstrusModal, //智能发情帖
    DeviceBasaModal, //巴杀
    DeviceSlurryscraperModal, //刮粪板
    DeviceDrinkheartingModal, //饮水供暖设备
    DeviceRollershadesModal, //卷帘设备
    DeviceStomachModal, //胃丸设备
    DeviceSpraycameraModal, //AI相机
    DeviceSprayfanlinkcameraModal, //AI相机风机联动
    DeviceAiedgecomputerModal, //AI边缘计算器
    DevicePowerMonitorModal, //电能终端监测系统
    EditOutlined,
    CheckOutlined,
    CloseOutlined,
  },
  data() {
    return {
      columns: [
        {
          title: '设备类型',
          dataIndex: 'deviceName',
          width: 85,
        },
        {
          title: '设备ID',
          dataIndex: 'recordId',
          width: 90,
          customRender: function(row) {
            let hexStr = parseInt(row.text).toString(16);
            return row.text + '(0x' + hexStr + ')';
          }
        },
        {
          title: '设备标签号',
          dataIndex: 'clientNum',
          width: 90,
        },
        {
          title: '标签(编号)',
          dataIndex: 'lable1',
          width: 80,
        },
        {
          title: '设备状态',
          key : 'statuscolumn',
          dataIndex: 'recordStatus',
          width: 65,
        },
        {
          title: '牧场',
          dataIndex: 'ranchName',
          width: 90,
        },
        {
          title: '牛舍',
          dataIndex: 'oxtallName',
          width: 90,
        },
        {
          title: '区域',
          dataIndex: 'areaName',
          width: 90,
        },
        {
          title: '牛栏',
          dataIndex: 'fenceName'
        },
        {
          title: '当前版本',
          dataIndex: 'clientVersion'
        },
        {
          title: '排序字段',
          dataIndex: 'csort',
          width: 115,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          key: 'action',
          width: 140,
          align: 'center',
          fixed: 'right',
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      devicetypeList : [],
      showDeviceManager : false,
      ranchList : [],
      oxtallList : [],
      areaList : [],
      currentView : '',
      //开关
      phaseView : '',
      showPhaseManager : false,
      phaseCurrenData : null,
      editingId: null,
      editingValue: null,
      // 添加新的编辑状态变量
      editingField: null,
      editingRanchId: null,
      editingOxtallId: null,
      editingAreaId: null,
      // 临时存储编辑时的选项列表
      tempRanchList: [],
      tempOxtallList: [],
      tempAreaList: [],
      editingFenceId: null,
      tempFenceList: [],
    };
  },
  async created() {
    let list = await DeviceApi.tree()
    let that = this;
    this.devicetypeList = (list ? list.data : null) || []
    RanchApi.list({}).then(resp => {
      let _ranchList = (resp ? resp.data : null) || [];
      this.ranchList = _ranchList;
      if (_ranchList.length > 0) {
        OxtallApi.list({"orgId" : _ranchList[0].ranchId}).then(result => {
          this.oxtallList = (result ? result.data : null) || [];
          if (this.oxtallList.length > 0) {
            AreaApi.list({"oxtId" : this.oxtallList[0].oxtallId}).then(result => {
              that.areaList = (result? result.data : null) || [];
            }).catch((err) => {
              console.log(err)
            });
          }
        }).catch((err) => {
          console.log(err)
        });
      }
    });
  },
  methods: {
    clearRanchRelated() {
      // 清空牛舍选择
      this.where.oxtId = undefined;
      // 清空区域选择
      this.where.areaId = undefined;
      // 清空相关列表数据
      this.oxtallList = [];
      this.areaList = [];
    },
    clearOxtallRelated() {
      // 清空区域选择
      this.where.areaId = undefined;
      this.areaList = [];
    },
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2022/03/05 14:43
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    reloadCurrent(){
      const page = this.$refs.table.tablePagination.current || 1;
      this.$refs.table.reload({ page: page });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2022/03/05 14:43
     */
    reset() {
      this.where.recordNo = '';
      this.where.oxtId = '';
      this.where.orgId = '';
      this.where.recordId = '';
      this.where.areaId = '';
      this.where.recordStatus = '';
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2022/03/05 14:43
     */
    async remove(row) {
      const result = await DeviceRecordApi.delete({ recordId: row.recordId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2022/03/05 14:43
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },

    openManager(row)
    {
      this.currentView = row.antdvComponent;
      this.current = row;
      this.showDeviceManager = true;
    },

    openPhaseManager(row)
    {
      this.phaseView = row.antdvComponent;
      this.phaseCurrenData = row;
      this.showPhaseManager = true;
    },

    selectRanch(ranchId) {
      this.oxtallList = [];
      this.areaList = [];
      this.where.areaId = undefined;
      this.where.oxtId = undefined;
      let that = this;
      OxtallApi.list({"orgId" : ranchId}).then(result => {
        this.oxtallList = (result ? result.data : null) || [];
        if (this.oxtallList.length > 0) {
          AreaApi.list({"oxtId" : this.oxtallList[0].oxtallId}).then(result => {
            that.areaList = (result? result.data : null) || [];
          }).catch((err) => {
            console.log(err)
          });
        }
      }).catch((err) => {
        console.log(err)
      });
    },

    selectOxtall(oxtId) {
      this.areaList = [];
      this.where.areaId = undefined;
      let that = this;
      AreaApi.list({"oxtId" : oxtId}).then(result => {
        that.areaList = (result? result.data : null) || [];
      }).catch((err) => {
        console.log(err)
      });
    },

    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({ page, limit, where, orders }) {
      return DeviceRecordApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },
    /**
     * 开始编辑排序字段
     */
    startEdit(record) {
      this.editingId = record.recordId;
      this.editingField = 'csort';  // 添加这一行
      this.editingValue = record.csort;
    },

    /**
     * 取消编辑
     */
    cancelEdit() {
      this.editingId = null;
      this.editingValue = null;
      this.editingField = null;
      this.editingRanchId = null;
      this.editingOxtallId = null;
      this.editingAreaId = null;
      this.editingFenceId = null;
    },

    /**
     * 开始编辑牧场
     */
    async startEditRanch(record) {
      this.editingId = record.recordId;
      this.editingField = 'ranchName';
      this.editingRanchId = record.orgId == 0 ? undefined : record.orgId;
      
      // 获取牧场列表
      try {
        const resp = await RanchApi.list({});
        this.tempRanchList = (resp ? resp.data : null) || [];
      } catch (err) {
        console.log(err);
        message.error('获取牧场列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存牧场
     */
    async saveRanch(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          orgId: this.editingRanchId,
          // 清空牛舍和区域信息
          oxtId: 0,
          areaId: 0,
          fenceId: 0,
        };
        
        await DeviceRecordApi.editCsort(updateData);
        message.success('牧场更新成功');
        
        // 更新当前记录的牧场信息
        const selectedRanch = this.tempRanchList.find(item => item.ranchId === this.editingRanchId);
        if (selectedRanch) {
          record.orgId = selectedRanch.ranchId;
          record.ranchName = selectedRanch.ranchName;
          // 清空牛舍和区域信息，因为牧场变了
          record.oxtId = null;
          record.oxtallName = '';
          record.areaId = null;
          record.areaName = '';
          record.fenceId = null;
          record.fenceName = '';
        }
        
        this.cancelEdit();
      } catch (error) {
        message.error('牧场更新失败' + (error.message || '未知错误'));
      }
    },

    /**
     * 开始编辑牛舍
     */
    async startEditOxtall(record) {
      if (!record.orgId) {
        message.warning('请先设置牧场');
        return;
      }
      
      this.editingId = record.recordId;
      this.editingField = 'oxtallName';
      this.editingOxtallId = record.oxtId == '0'? undefined : record.oxtId;
      
      // 获取牛舍列表，基于当前记录的牧场ID
      try {
        const result = await OxtallApi.list({"orgId": record.orgId});
        this.tempOxtallList = (result ? result.data : null) || [];
        if (this.tempOxtallList.length === 0) {
          message.warning('当前牧场下没有牛舍');
        }
      } catch (err) {
        console.log(err);
        message.error('获取牛舍列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存牛舍
     */
    async saveOxtall(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          oxtId: this.editingOxtallId,
          // 清空区域和牛栏信息
          areaId: 0,
          fenceId: 0
        };
        
        await DeviceRecordApi.editCsort(updateData);
        message.success('牛舍更新成功');
        
        // 更新当前记录的牛舍信息
        const selectedOxtall = this.tempOxtallList.find(item => item.oxtallId === this.editingOxtallId);
        if (selectedOxtall) {
          record.oxtId = selectedOxtall.oxtallId;
          record.oxtallName = selectedOxtall.oxtallName;
          // 清空区域和牛栏信息，因为牛舍变了
          record.areaId = null;
          record.areaName = '';
          record.fenceId = null;
          record.fenceName = '';
        }
        
        this.cancelEdit();
      } catch (error) {
        message.error('牛舍更新失败' + (error.message || '未知错误'));
      }
    },

    /**
     * 开始编辑区域
     */
    async startEditArea(record) {
      if (!record.oxtId) {
        message.warning('请先设置牛舍');
        return;
      }
      
      this.editingId = record.recordId;
      this.editingField = 'areaName';
      this.editingAreaId = record.areaId == '0'? undefined : record.areaId;
      
      // 获取区域列表，基于当前记录的牛舍ID
      try {
        const result = await AreaApi.list({"oxtId": record.oxtId});
        this.tempAreaList = (result ? result.data : null) || [];
        if (this.tempAreaList.length === 0) {
          message.warning('当前牛舍下没有区域');
        }
      } catch (err) {
        console.log(err);
        message.error('获取区域列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存区域
     */
    async saveArea(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          areaId: this.editingAreaId
        };
        
        await DeviceRecordApi.editCsort(updateData);
        message.success('区域更新成功');
        
        // 更新当前记录的区域信息
        const selectedArea = this.tempAreaList.find(item => item.areaId === this.editingAreaId);
        if (selectedArea) {
          record.areaId = selectedArea.areaId;
          record.areaName = selectedArea.areaName;
        }
        
        this.cancelEdit();
      } catch (error) {
        message.error('区域更新失败' + (error.message || '未知错误'));
      }
    },
    /**
     * 开始编辑牛栏
     */
    async startEditFence(record) {
      if (!record.oxtId) {
        message.warning('请先设置牛舍');
        return;
      }
      
      this.editingId = record.recordId;
      this.editingField = 'fenceName';
      this.editingFenceId = record.fenceId == '0'? undefined : record.fenceId;
      
      // 获取牛栏列表，基于当前记录的牛舍ID
      try {
        // 假设有一个 FenceApi.list 方法用于获取牛栏列表
        const result = await FenceApi.list({"oxtId": record.oxtId});
        this.tempFenceList = (result ? result.data : null) || [];
        if (this.tempFenceList.length === 0) {
          message.warning('当前牛舍下没有牛栏');
        }
      } catch (err) {
        console.log(err);
        message.error('获取牛栏列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存牛栏
     */
    async saveFence(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          fenceId: this.editingFenceId
        };
        let that = this;
        DeviceRecordApi.editCsort(updateData).then(() => {
          message.success('牛栏更新成功');
            // 更新当前记录的牛栏信息
          const selectedFence = that.tempFenceList.find(item => item.fenceId === that.editingFenceId);
          if (selectedFence) {
            record.fenceId = selectedFence.fenceId;
            record.fenceName = selectedFence.fenceName;
          }
          
          that.cancelEdit();
        }).catch((error) => {
          console.error('牛栏更新失败:', error);
          message.error('牛栏更新失败: ' + (error.message || '未知错误'));
        });  
      } catch (err) {
        message.error('牛栏更新失败' + (err.message || '未知错误'));
      }
    },
    /**
     * 保存排序值
     */
    async saveSort(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          csort: this.editingValue
        };
        
        await DeviceRecordApi.editCsort(updateData);
        message.success('排序更新成功');
        record.csort = this.editingValue;
        this.cancelEdit();
      } catch (error) {
        message.error('排序更新失败');
      }
    },

  }
};
</script>
